package cn.tedu.charging.order.rabbitmq;

import cn.tedu.charging.order.config.RabbitMQConfiguration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class RabbitMQProducer {

    private static final Logger log = LoggerFactory.getLogger(RabbitMQProducer.class);
    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 发送消息
     *
     * @param msg
     */
    public void send(String msg) {

        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack)   {
                log.debug("消息发送成功,RabbitMQ成功的收到了消息");
            } else {
                log.debug("消息发送失败,RabbitMQ没有收到消息");
                log.debug("失败原因:{}", cause);
                log.debug("如果失败进行重试，重试几次后，还不成功，监控告警");
            }
        });


        //消息持久化
        Message message = new Message(msg.getBytes(), new MessageProperties());
        //消息持久化
        message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
        rabbitTemplate.convertAndSend
                (RabbitMQConfiguration.EXCHANGE_NAME,
                        RabbitMQConfiguration.ROUTING_KEY, msg);
        //发送消息 发送到 Exchange 和 routingKey 和具体的消息
        //channel.basicPublish(exchange, routingKey, null, message.getBytes());
    }


}
